#  Imports
import pygame, math, sys, random
from Player import Player
from Map import Level
from Block import Block
from Menu import Button
from EnemyBase import EnemyBase
from CollideBlock import CollideBlock
from ConfigReader import ConfigReader
from Screen import Screen
from KillBlock import KillBlock
from SpawnBlock import SpawnBlock
from FallBlock import FallBlock


if pygame.mixer:
    pygame.mixer.init()

pygame.init()

clock = pygame.time.Clock()
ECounter = 0
screenWidth = 800
screenHeight = 600

screenSize = screenWidth, screenHeight
screen = pygame.display.set_mode(screenSize)

run = False
menu = False
high = False
options = False
init = True
pause = False
load = False

# Init
while True:
    while init:
#        EnemyBase = pygame.sprite.Group()
        blocks = pygame.sprite.Group()
        collideBlocks = pygame.sprite.Group()
        SpawnBlocks = pygame.sprite.Group()
        FallBlocks = pygame.sprite.Group()
        enemies = pygame.sprite.Group()
        KillBlocks = pygame.sprite.Group()
        all = pygame.sprite.OrderedUpdates()
     
        
        Player.containers = all
        EnemyBase.containers = all, enemies
        Block.containers = all, blocks
        CollideBlock.containers = all, collideBlocks
        KillBlock.containers = all, KillBlocks
        SpawnBlock.containers = all, SpawnBlocks
        SpawnBlock.containers = all, FallBlocks
        
        # Menu stuff
        
        start = Button("SINGLEPLAYER", [250,300], (200, 10, 10))
        load = False
        option = Button("OPTIONS", [250,400], (200, 10, 10))
        exit = Button("EXIT", [250,500], (200, 10, 10))
        background = Screen(["rsc/imgs/background_10.png",
                            "rsc/imgs/background_9.png", 
                            "rsc/imgs/background_8.png", 
                            "rsc/imgs/background_7.png", 
                            "rsc/imgs/background_6.png", 
                            "rsc/imgs/background_5.png", 
                            "rsc/imgs/background_1.png", 
                            "rsc/imgs/background_2.png", 
                            "rsc/imgs/background_3.png", 
                            "rsc/imgs/background_.5.png"], [0,0])                 
        
        #Key Config
        keyCount = 0
        
        keycode = Button("KEY CONFIG", [100,50], (200, 10, 10))
        
        keyConfig = ConfigReader()
        keyConfig.read("rsc/config/keyconfig.txt")
        
        keynames = ["w", "a", "d", "j", "tab"]
        keys = [pygame.K_w, pygame.K_a, pygame.K_d, pygame.K_j, pygame.K_TAB]
        
        for i in range(len(keyConfig.values)):
            keys[keyCount] = int(keyConfig.values[keyCount][1])
            keynames[keyCount] = pygame.key.name(int(keyConfig.values[keyCount][1]))
            keyCount += 1
        
        buttonUp = Button("UP = " + str(keys[0]), [150,150], (200, 10, 10))
        buttonLeft = Button("LEFT = " + str(keys[1]), [150,200], (200, 10, 10))
        buttonRight = Button("RIGHT = " + str(keys[2]), [150,250], (200, 10, 10))
        buttonAction = Button("ACTION = " + str(keys[3]), [150,300], (200, 10, 10))
        buttonPause = Button("PAUSE = " + str(keys[4]), [150,350], (200, 10, 10))
        
        configKey = False
        
        map = Level("test3", screenSize)
        enemyList = []
        for block in map.playerblocks:
            player = Player(block.rect.center, screenSize)

        bgColor = 0,0,0

        # enemy.place([450, 400])
        
        init = False
        menu = True
        
        
    # Menu
    while menu:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if start.collidePt(event.pos):
                        start.clicked = True
                        run = True  
                        menu = False
                    elif option.collidePt(event.pos):
                        option.clicked = True
                        options = True  
                        menu = False    
                    elif exit.collidePt(event.pos):
                        exit.clicked = True
                        sys.exit()

        start.update((200, 10, 10))
        option.update((200, 10, 10))
        exit.update((200, 10, 10))
        
        background.animate(100, False)
        
        screen.fill(bgColor)
        screen.blit(background.image, background.rect)
        screen.blit(option.surface, option.rect)
        screen.blit(start.surface, start.rect)
        screen.blit(exit.surface, exit.rect)
        pygame.display.flip()
        
    # Options
    while options:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:                  
                    if keycode.collidePt(event.pos):
                        option.clicked = True
                        configKey = True
                    elif exit.collidePt(event.pos):
                        exit.clicked = True
                        options = False
                        menu = True
                    elif buttonUp.collidePt(event.pos):
                        buttonUp.clicked = True
                        buttonLeft.clicked = False
                        buttonRight.clicked = False
                        buttonPause.clicked = False
                        buttonAction.clicked = False
                    elif buttonLeft.collidePt(event.pos):
                        buttonUp.clicked = False
                        buttonLeft.clicked = True
                        buttonRight.clicked = False
                        buttonPause.clicked = False
                        buttonAction.clicked = False
                    elif buttonRight.collidePt(event.pos):
                        buttonUp.clicked = False
                        buttonLeft.clicked = False
                        buttonRight.clicked = True
                        buttonPause.clicked = False
                        buttonAction.clicked = False
                    elif buttonPause.collidePt(event.pos):
                        buttonUp.clicked = False
                        buttonLeft.clicked = False
                        buttonRight.clicked = False
                        buttonPause.clicked = True
                        buttonAction.clicked = False
                    elif buttonAction.collidePt(event.pos):
                        buttonUp.clicked = False
                        buttonLeft.clicked = False
                        buttonRight.clicked = False
                        buttonPause.clicked = False
                        buttonAction.clicked = True    
                        
            if buttonUp.clicked and event.type == pygame.KEYDOWN:
                keys[0] = event.key
                keynames[0] = pygame.key.name(event.key)
                keyConfig.canRun = True
                keyConfig.reload("rsc/config/keyconfig.txt", "up", event.key)
            elif buttonLeft.clicked and event.type == pygame.KEYDOWN:
                keys[1] = event.key
                keynames[1] = pygame.key.name(event.key)
                keyConfig.canRun = True
                keyConfig.reload("rsc/config/keyconfig.txt", "left", event.key)
            elif buttonRight.clicked and event.type == pygame.KEYDOWN:
                keys[2] = event.key    
                keynames[2] = pygame.key.name(event.key)
                keyConfig.canRun = True
                keyConfig.reload("rsc/config/keyconfig.txt", "right", event.key)
            elif buttonAction.clicked and event.type == pygame.KEYDOWN:
                keys[3] = event.key    
                keynames[3] = pygame.key.name(event.key)
                keyConfig.canRun = True
                keyConfig.reload("rsc/config/keyconfig.txt", "action", event.key)    
            elif buttonPause.clicked and event.type == pygame.KEYDOWN:
                keys[4] = event.key    
                keynames[4] = pygame.key.name(event.key)
                keyConfig.canRun = True
                keyConfig.reload("rsc/config/keyconfig.txt", "tab", event.key)    
        
        # keyConfig.update((200, 10, 10))
        exit.update((200, 10, 10))
        buttonUp.update2("UP = " + str(keynames[0]), (200, 10, 10))
        buttonLeft.update2("LEFT = " + str(keynames[1]), (200, 10, 10))
        buttonRight.update2("RIGHT = " + str(keynames[2]), (200, 10, 10))
        buttonAction.update2("ACTION = " + str(keynames[3]), (200, 10, 10))
        buttonPause.update2("PAUSE = " + str(keynames[4]), (200, 10, 10))
            
        screen.fill(bgColor)
        screen.blit(keycode.surface, keycode.rect)
        screen.blit(buttonUp.surface, buttonUp.rect)
        screen.blit(buttonLeft.surface, buttonLeft.rect)
        screen.blit(buttonRight.surface, buttonRight.rect)
        screen.blit(buttonAction.surface, buttonAction.rect)
        screen.blit(buttonPause.surface, buttonPause.rect)
        # if not buttonKeyConfig.living:
            # screen.blit(buttonKeyConfig.surface, buttonKeyConfig.rect)
        # screen.blit(option.surface, option.rect)
        # screen.blit(singleplayer.surface, singleplayer.rect)
        screen.blit(exit.surface, exit.rect)
        pygame.display.flip()
            
    while run:
        # Key inputs
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == keys[1]:
                    player.direction("left")
                elif event.key == keys[2]:
                    player.direction("right")
                if event.key == keys[0]:
                    player.canJump = 1   
                if event.key == keys[4]:
                    pause = True
                    run = False
                if event.key == keys[3]:
                    player.canShoot = True
                    
            if event.type == pygame.KEYUP:
                if event.key == keys[1]:
                    player.direction("stop left")
                elif event.key == keys[2]:
                    player.direction("stop right")
                if event.key == keys[0]:
                    player.canJump = 0
                if event.key == keys[3]:
                    player.canShoot = False    
                    
        
        
        #Code for creatin enemies and projectiles
        #Code for sutff that happens in game
        
        # enemy functions and collisions     

        playerHitBlocks = pygame.sprite.spritecollide(player, collideBlocks, False)
        #mine block#
        MineBlocks = pygame.sprite.spritecollide(player, KillBlocks, False)
        
        player.shoot()
        # player.gravity()
        
        if len(playerHitBlocks) == 0:
            player.onGround = False
        
        for block in playerHitBlocks:
            player.blockCollide(block)
        
        if ECounter < 5:
            for block in map.enemyblocks:
                enemyList = EnemyBase([5,5], block.rect.center, screenSize)
                ECounter += 1  
        # for block in playerHitBlocks:
            # player.blockCollide(block)
            
        for block in SpawnBlocks:
            if block.didPlace:
                enemyList += [EnemyBase([5,5], block.rect.center, screenSize)]
                block.didPlace = False
        for block in MineBlocks:
            player.living = False
        
        all.update(player)   
        
        
#        for Block in FallBlocks: 
#            Block.fall(player)
        
        if not player.living:
            run = False 
            init = True
             
        # Health Code
        # Blits
        dirty = all.draw(screen)
        pygame.display.update(dirty)
        clock.tick(30)
        
    while pause:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == keys[4]:
                    pause = False
                    run = True

            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if option.collidePt(event.pos):
                        option.clicked = True
                        options = True  
                        pause = False    
                    elif exit.collidePt(event.pos):
                        exit.clicked = True
                        pause = False
                        init = True

        option.update((200, 10, 10))
        exit.update((200, 10, 10))
        
        
        screen.blit(option.surface, option.rect)
        screen.blit(exit.surface, exit.rect)
        
        pygame.display.flip() 
        
    # Loop for Highscore
    while high:
        # stop smoking your joint taylor
        # Stuff for high score
        # Blit
        pass


